package com.example.fastdfsdemo.util;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * 日期和字符串转换器
 * @author 276834
 */
public class DateAndStringExchanger {

    private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * jdk8下将Date 转为 LocalDate
     * 获取Date对应的格式化字符串
     * @param date
     * @return
     */
    public static String getDateFormatString(Date date){
        LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
        LocalDate localDate = localDateTime.toLocalDate();
        return localDate.format(formatter);
    }

    /**
     * jdk8下将Date 转为 localDateTime
     * 获取Date对应精确到时分秒的格式化字符串
     * @param date
     * @return
     */
    public static String getDatetimeFormatString(Date date){
        LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
        return localDateTime.format(formatter);
    }


    /**
     * 字符串 转为 日期
     */
    public static Date localDateTimeToDate(String dateString) {
        LocalDateTime localDateTime = LocalDateTime.parse(dateString, formatter);
        ZoneId zone = ZoneId.systemDefault();
        Instant instant = localDateTime.atZone(zone).toInstant();
        java.util.Date date = Date.from(instant);
        return date;
    }

    /**
     * 字符串 转为 日期
     */
    public static Date dateToLocalDateTime(LocalDateTime localDateTime) {
        ZoneId zone = ZoneId.systemDefault();
        Instant instant = localDateTime.atZone(zone).toInstant();
        java.util.Date date = Date.from(instant);
        return date;
    }

    /**
     * LocalDateTime 转为 格式化日期字符串
     */
    public static String localDateTimeToString(LocalDateTime localDateTime) {
        ZoneId zone = ZoneId.systemDefault();
        Instant instant = localDateTime.atZone(zone).toInstant();
        java.util.Date date = Date.from(instant);
        return DateAndStringExchanger.getDateFormatString(date);
    }

    /**
     * jdk8下LocalDateTime 转为 Date
     */
    public static void localDateTimeToDate() {
        LocalDateTime localDateTime = LocalDateTime.now();
        ZoneId zone = ZoneId.systemDefault();
        Instant instant = localDateTime.atZone(zone).toInstant();
        java.util.Date date = Date.from(instant);
    }

    /**
     * jdk8下LocalDate 转为 Date
     */
    public static void localTimeToDate() {
        LocalTime localTime = LocalTime.now();
        LocalDate localDate = LocalDate.now();
        LocalDateTime localDateTime = LocalDateTime.of(localDate, localTime);
        ZoneId zone = ZoneId.systemDefault();
        Instant instant = localDateTime.atZone(zone).toInstant();
        java.util.Date date = Date.from(instant);
    }
}
